package link.config;

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import org.an.ku.util.ACache;
import org.an.proj.contacts.MyApplication;
import org.an.proj.contacts.model.bean.ConfigInfoVo;

/**
 * Created by an on 2016/12/18.<br/>
 * 存储用户登录状态，token，配置信息等
 */

public class StoreConfig {
  private static final String CONFIG_NAME = "StoreConfig";
  private static final String KEY_TOKEN = "token";
  private static final String KEY_IS_LOGIN = "is_login";
  private static final String KEY_CONFIGINFO = "configinfo";

  private static final String KEY_PASSWORD = "password";
  private static final String KEY_USERNAME = "username";

  private static StoreConfig mInstance;
  // 使用SharedPreferences存储简单的数据，使用ACache 存储大的json数据。
  // 防止sp太大，解析慢
  private SharedPreferencesHelper mSpHelp;
  private ACache mACache;

  private StoreConfig() {
    mSpHelp = SharedPreferencesHelper.create(CONFIG_NAME);
    mACache = ACache.get(MyApplication.getInstance(), CONFIG_NAME);
  }

  public static StoreConfig getInstance() {
    if (mInstance == null) {
      synchronized (StoreConfig.class) {
        if (mInstance == null) {
          mInstance = new StoreConfig();
        }
      }
    }
    return mInstance;
  }

  public void setToken(String token) {
    mSpHelp.putString(KEY_TOKEN, token);
  }

  @Nullable public String getToken() {
    return mSpHelp.getString(KEY_TOKEN, null);
  }

  public void setLogin(boolean isLogin) {
    mSpHelp.putBoolean(KEY_IS_LOGIN, isLogin);
  }

  public boolean isLogin() {
    return mSpHelp.getBoolean(KEY_IS_LOGIN, false);
  }

  public void setConfigInfo(@Nullable ConfigInfoVo configInfoVo) {
    if (configInfoVo != null) {
      mACache.put(KEY_CONFIGINFO, configInfoVo);
    }
  }

  public void setUserName(String userName) {
    mSpHelp.putString(KEY_USERNAME, userName);
  }

  public String getUserName() {
    return mSpHelp.getString(KEY_USERNAME, null);
  }

  public void setPassword(String password) {
    mSpHelp.putString(KEY_PASSWORD, password);
  }

  public String getPassword() {
    return mSpHelp.getString(KEY_PASSWORD, null);
  }

  @NonNull public ConfigInfoVo getConfigInfo() {
    Object object = mACache.getAsObject(KEY_CONFIGINFO);
    if (object == null) return new ConfigInfoVo();
    return (ConfigInfoVo) object;
  }
}
